package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.OpDeliveryHistory;
import cn.com.hhrcw.entity.OpJob;
import cn.com.hhrcw.entity.SsSession;
import cn.com.hhrcw.mapstruct.AdminSsSessionConvert;
import cn.com.hhrcw.params.SsSessionAdminParams;
import cn.com.hhrcw.params.SsSessionParams;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.vo.SsDataInfoVO;
import cn.com.hhrcw.vo.SsSessionVO;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 专场
 *
 * @author jiangdong
 * @since 2020-10-29
 */
@RestController
@Slf4j
@RequestMapping("/admin/ssSession")
@Api(tags = "专场-专场本场")
@Validated
public class AdminSsSessionController extends JeecgController<SsSession, ISsSessionService> {

    @Autowired
    private ISsSessionService ssSessionService;

    @Autowired
    private AdminSsSessionConvert enSsSessionConvert;

    @Autowired
    private IOpJobService jobService;

    @Autowired
    private IOpDeliveryHistoryService deliveryHistoryService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private ISysUserDepartService userDepartService;

    /**
     * 专场招聘-招聘数据
     *
     * @param ssId 专场id
     * @return
     */
    @GetMapping(value = "/getDataInfo")
    @AutoLog(logType = 2, ty = "visit", value = "专场-招聘数据")
    public Result<SsDataInfoVO> getDataInfo(String ssId) {
        SsDataInfoVO infoVO = adminService.getDatInfo(ssId);
        return Result.ok(infoVO);
    }

    /**
     * 专场添加
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog(logType = 2, ty = "insert", value = "添加专场")
    public Result<?> add(@RequestBody @Valid SsSessionParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Integer count = service.lambdaQuery().eq(SsSession::getTitle, params.getTitle()).eq(SsSession::getDelFlag, false).count();
        Assert.isFalse(count > 0, "专场名称已存在");
        SsSession ssSession = enSsSessionConvert.toEntity(params);
        ssSession.setCreateBy(sysUser.getId());
        ssSession.setCreateTime(DateUtil.date());
        ssSession.setDelFlag(false);
        ssSession.setRecommendFlag(0);
        ssSession.setPubFlag(false);
        if(params.getPostShelfManage()){
            ssSession.setPostShelfManage(true);
            ssSession.setPostStatus("0");
        }else{
            ssSession.setPostShelfManage(false);
        }
        boolean saved = ssSessionService.save(ssSession);
        return saved ? Result.ok() : Result.error("添加失败");
    }

    /**
     * 专场编辑
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog(logType = 2, ty = "updaet", value = "专场编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("session:edit")
    public Result<?> edit(@RequestBody @Valid SsSessionParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SsSession ssSession = enSsSessionConvert.toEntity(params);
        ssSession.setUpdateBy(sysUser.getId());
        ssSession.setUpdateTime(DateUtil.date());
        if(params.getPostShelfManage()){
            ssSession.setPostShelfManage(true);
            if(StrUtil.isBlank(ssSession.getPostStatus())){
                ssSession.setPostStatus("0");
            }
        }else{
            ssSession.setPostShelfManage(false);
        }
        boolean updated = ssSessionService.updateById(ssSession);
        return updated ? Result.ok() : Result.error("编辑失败");
    }

    /**
     * 取消发布专场
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/unPublish")
    @AutoLog(logType = 2, ty = "update", value = "专场修改")
    @ApiOperation(value = "取消发布专场", notes = "取消发布专场")
    @RequiresPermissions("session:publish")
    public Result<?> unPublish(@RequestBody @Valid SsSessionParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SsSession ssSession = enSsSessionConvert.toEntity(params);
        ssSession.setUpdateBy(sysUser.getId());
        ssSession.setUpdateTime(DateUtil.date());
        ssSession.setPubFlag(false);
        ssSession.setUpdateTime(new Date());
        boolean updated = ssSessionService.updateById(ssSession);
        return updated ? Result.ok() : Result.error("编辑失败");
    }

    /**
     * 发布专场
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/publish")
    @AutoLog(logType = 2, ty = "update", value = "专场修改")
    @ApiOperation(value = "发布此专场", notes = "发布此专场")
    @RequiresPermissions("session:publish")
    public Result<?> publish(@RequestBody @Valid SsSessionParams params) {
        int jobCount = jobService.lambdaQuery().eq(OpJob::getBsType, 1).eq(OpJob::getBsId, params.getId()).count();
        if (jobCount == 0) {
            return Result.error("该专场未完善职位。");
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SsSession ssSession = enSsSessionConvert.toEntity(params);
        ssSession.setUpdateBy(sysUser.getId());
        ssSession.setUpdateTime(DateUtil.date());
        ssSession.setPubFlag(true);
        ssSession.setPubTime(new Date());
        boolean updated = ssSessionService.updateById(ssSession);
        return updated ? Result.ok() : Result.error("编辑失败");
    }

    /**
     * 专场推荐
     *
     * @param params
     * @return
     */
    @PostMapping("/recommended")
    @AutoLog(value = "专场推荐", logType = 2, ty = "update")
    @RequiresPermissions("session:recommended")
    public Result recommended(@RequestBody SsSessionAdminParams params) {
        SsSession session = this.ssSessionService.getById(params.getId());
        int flag = session.getRecommendFlag() == 0 ? 1 : 0;
        session.setRecommendFlag(flag);
        if (flag == 1) {
            session.setRecommendSort(params.getRecommendSort());
        }
        boolean updated = this.ssSessionService.updateById(session);
        return updated ? Result.ok() : Result.error("推荐失败");
    }

    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/delete")
    @AutoLog(logType = 2, ty = "delete", value = "专场删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("session:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<SsSession> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(SsSession::getId, id).set(SsSession::getDelFlag, true).set(SsSession::getUpdateBy, sysUser.getUsername()).set(SsSession::getUpdateTime, DateUtil.date());
        List<OpJob> jobList = jobService.lambdaQuery()
            .eq(OpJob::getBsType, 1)
            .in(OpJob::getBsId, id)
            .list();
        if(CollUtil.isNotEmpty(jobList)){
            jobList.stream().map(e -> e.setDelFlag(true)).forEach(jobService::updateById);
        }
        boolean deleted = ssSessionService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    @PostMapping(value = "/postOnline")
    @AutoLog(logType = 2, ty = "update", value = "专场岗位上线")
    @ApiOperation(value = "专场岗位上线", notes = "专场岗位上线")
    @RequiresPermissions("session:postOnline")
    public Result<?> postOnline(@RequestBody @Valid SsSessionParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SsSession session = this.ssSessionService.getById(params.getId());
        if(session.getPostShelfManage()){

        }else{
            return Result.error("该专场不管控岗位发布和关闭");
        }
        session.setUpdateBy(sysUser.getId());
        session.setPostStatus("1");
        session.setUpdateTime(new Date());
        boolean updated = ssSessionService.updateById(session);

        List<OpJob> opJobList = jobService.lambdaQuery()
                .eq(OpJob::getBsId, session.getId())// 专场id
                .eq(OpJob::getBsId, session.getId())// 专场id
                .eq(OpJob::getBsType, "1") // 专场类型
                .eq(OpJob::getDelFlag, false).list();
        if(CollUtil.isEmpty(opJobList)){
            return Result.error("该专场下暂无职位信息");
        }
        for (OpJob job : opJobList) {
            job.setRecruitmentState(0);
            job.setCloseTime(null);
            job.setUpdateBy(sysUser.getId());
            job.setUpdateTime(new Date());
            this.jobService.updateRecruitmentState(job);
        }
        return updated ? Result.ok() : Result.error("编辑失败");
    }

    @PostMapping(value = "/postOutline")
    @AutoLog(logType = 2, ty = "update", value = "专场岗位下线")
    @ApiOperation(value = "专场岗位下线", notes = "专场岗位下线")
    public Result<?> postOutline(@RequestBody @Valid SsSessionParams params) {
        SsSession session = this.ssSessionService.getById(params.getId());
        if(session.getPostShelfManage()){

        }else{
            return Result.error("该专场不管控岗位发布和关闭");
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        session.setUpdateBy(sysUser.getId());
        session.setPostStatus("2");
        session.setUpdateTime(new Date());
        boolean updated = ssSessionService.updateById(session);
        List<OpJob> opJobList = jobService.lambdaQuery()
                .eq(OpJob::getBsId, session.getId())// 专场id
                .eq(OpJob::getBsType, "1") // 专场类型
                .eq(OpJob::getDelFlag, false).list();
        if(CollUtil.isEmpty(opJobList)){
            return Result.error("该专场下暂无职位信息");
        }
        for (OpJob job : opJobList) {
            if (job.getRecruitmentState() == 1) {
                continue;
            }
            job.setRecruitmentState(1);
            job.setCloseTime(DateUtil.date());
            job.setUpdateBy(sysUser.getId());
            job.setUpdateTime(new Date());
            this.jobService.updateRecruitmentState(job);
        }
        return updated ? Result.ok() : Result.error("编辑失败");
    }

    /**
     * 专场列表
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog(value = "专场列表", logType = 2, ty = "visit")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @PermissionData
    public Result<Page<SsSessionVO>> list(SsSessionParams params, HttpServletRequest request) {
        LambdaQueryWrapper<SsSession> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SsSession::getDelFlag, false);
        if (StrUtil.isNotBlank(params.getTitle())) {
            queryWrapper.like(SsSession::getTitle, params.getTitle());
        }
        if (params.getStartTime() != null && params.getEndTime() != null) {
            queryWrapper.isNotNull(SsSession::getPubTime).le(SsSession::getPubTime, params.getEndTime())
                .ge(SsSession::getPubTime, params.getStartTime());
        }
        //发布状态
        if (params.getPubFlag() != null) {
            queryWrapper.eq(SsSession::getPubFlag, params.getPubFlag());
        }
        Date date = new Date();
        int two = 2;
        int three = 3;
        //进行中
        if (1 == params.getTimeState()) {
            queryWrapper.le(SsSession::getStartTime, date).gt(SsSession::getEndTime, date);
        } else if (two == params.getTimeState()) {
            //未开始
            queryWrapper.gt(SsSession::getStartTime, date);
        } else if (three == params.getTimeState()) {
            //已结束
            queryWrapper.lt(SsSession::getEndTime, date);
        }
        queryWrapper.orderByDesc(SsSession::getCreateTime);
        List<DictModel> models = sysBaseApi.queryDictItemsByCode("gxt_ss_session");
        if(CollUtil.isNotEmpty(models)){
            queryWrapper.in(SsSession::getId, models.stream().map(DictModel::getValue).toArray());
        }else{
            queryWrapper.eq(SsSession::getId,"null");
        }
        IPage<SsSession> page = ssSessionService.page(params.page(), queryWrapper);

        IPage<SsSessionVO> iPage = page.convert(el -> {
            SsSessionVO vo = enSsSessionConvert.toVO(el);
            vo.setPostShelfManage(el.getPostShelfManage());
            vo.setPostStatus(el.getPostStatus());
            boolean isIn = DateUtil.isIn(DateUtil.date(), vo.getStartTime(), vo.getEndTime());
            if (isIn) {
                vo.setStatus("进行中");
            } else if (DateUtil.between(vo.getStartTime(), DateUtil.date(), DateUnit.MINUTE, false) < 0) {
                vo.setStatus("未开始");
            } else {
                vo.setStatus("已结束");
            }
            //职位数量
            LambdaQueryWrapper<OpJob> jobQuery = new LambdaQueryWrapper<>();
            jobQuery.eq(OpJob::getDelFlag, false).eq(OpJob::getBsType, 1).eq(OpJob::getBsId, vo.getId()).select(OpJob::getId);
            List<OpJob> job = jobService.list(jobQuery);
            if (!CollectionUtils.isEmpty(job)) {
                vo.setJobCount(job.size());
                List<String> jobIds = new ArrayList<>();
                job.forEach(e -> {
                    jobIds.add(e.getId());
                });
                LambdaQueryWrapper<OpDeliveryHistory> historyQuery = new LambdaQueryWrapper<>();
                historyQuery.eq(OpDeliveryHistory::getDelFlag, false).in(OpDeliveryHistory::getJobId, jobIds);
                int deliveryCount = deliveryHistoryService.count(historyQuery);
                vo.setUserCount(deliveryCount);
            }
            return vo;
        });

        return Result.ok((Page) iPage);
    }

}
